<template>
  <!-- 成员编辑对话框 -->
  <el-dialog
    v-model="visible"
    title="编辑成员信息"
    width="500px"
    :draggable="true"
    class="member-edit-dialog"
  >
    <el-form
      ref="editMemberForm"
      :model="localData"
      label-width="100px"
      :rules="editMemberRules"
      label-position="top"
    >
      <el-form-item label="成员姓名">
        <el-input
          v-model="localData.name"
          disabled
          clearable
        />
      </el-form-item>

      <el-form-item label="成员角色" prop="role">
        <el-select
          v-model="localData.role"
          placeholder="请选择角色"
          style="width: 100%"
        >
          <el-option
            v-for="role in roleList"
            :key="role.code"
            :label="role.desc"
            :value="role.code"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button color="#1F63FF" @click="submitMemberEdit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ElMessage, type FormInstance} from "element-plus";
import {computed, reactive, ref, watch} from "vue";
import type {Member} from "@/api/member/type.ts";
import {useRoleStore} from "@/stores/useRoleStore.ts";
import {storeToRefs} from "pinia";
import {updateMember} from "@/api/member";

const props = defineProps<{
  visible: boolean;
  data: Member;
}>();

const localData = ref<Member>({...props.data});
watch(() => props.data, (newVal) => {
  localData.value = newVal;
}, {deep: true})

const emit = defineEmits(['update:visible', 'refresh-member']);

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});
//角色列表
const {roleList} = storeToRefs(useRoleStore());


const editMemberForm = ref<FormInstance>();


const editMemberRules = reactive({
  role: [
    {required: true, message: '请选择成员角色', trigger: 'change'}
  ]
});
const submitMemberEdit = async () => {
  try {
    await editMemberForm.value?.validate();
    // 这里调用API保存编辑
    const res = await updateMember(localData.value);
    if (res.code === "M000") {
      ElMessage.success('成员信息更新成功');
      visible.value = false;
      emit('refresh-member');
    }


  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败，请检查表单');
  }
};
</script>

<style scoped lang="scss">

</style>
